package com.zcsy.manage.web.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.sms.dlife.DlifeSmsConfig;
import com.zcsy.commons.util.Globals;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.base.CellInfoDao;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.IVerifyCodeService;
import com.zcsy.manage.service.sms.DlifeSmsService;
import com.zcsy.manage.service.system.IMenuService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.common.SixCodeUtil;

/**
 * 
 * @Title: LoginController.java
 * @Package： com.zcsy.manage.web.system 
 * @Description: 登陆方法
 * @author chensf 735569870@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年1月8日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
public class LoginController {

	/**
	 * 日志创建对象<br>
	 */
	private static final Log log = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IMenuService menuService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private CellInfoDao cellInfoDao;
	
	@Autowired
	private DlifeSmsService dlifesmsService;
	
	@Autowired
	private IVerifyCodeService verifyCodeService;
	    
    private static final int USER_CHECK = 1;
	    
	private static final int PHONE_BIND = 2;
	
	@RequestMapping(value="login" , method = RequestMethod.GET)
	@ResponseBody
	public RequestJson login(String uname,String pwd,HttpServletRequest request,
			HttpServletResponse response) {
		final HttpSession session = request.getSession();
		RequestJson result = new RequestJson();
		try {
			//验证登录名和手机号
			User loginUser = new User();
			loginUser.setPhone(uname);
			loginUser.setUserType(Constants.ADMIN_TYPE);
			User user = userService.userLogin(loginUser);
			if (user == null) {
				result.setMsg("用户不存在");
				result.setSuccess(false);
				return result;
			}
			if(user.getState().intValue() != 1){
				result.setMsg("用户已停用");
				result.setSuccess(false);
			 	return result;
			}
			
			//前台用手机号或登录名加密的，但是数据库是用登录名加密存储的，所以要筛除掉手机号的情况
//			pwd = DESEncryption.decrypt(pwd, uname);
//			pwd = DESEncryption.encrypt(pwd, user.getLoginname());
//			final String userKey = MD5Util.generalPassword(user.getLoginname(), pwd);
			//密码校验
			if(pwd.equals(user.getPwd())){
				//取到用户对应的角色
				List<String> roleList = userService.selectRoleByUserId(user.getId());
				user.setRoleList(roleList);
				
				if (CollectionUtils.isEmpty(user.getRoleList())){
				 	result.setMsg("您没有任何权限，请联系管理员");
				 	result.setSuccess(false);
				 	return result;
				}
				
				//根据当前用户的角色list取出每个roleId对应的cellList取并集存入cellInfos
				List<CellInfo> cellInfos = new ArrayList<CellInfo>();
				if(user.getUserType() != Constants.ADMIN_TYPE){
					cellInfos = roleService.getCellInfosByRoleId(user.getRoleList());
					
					//没有任何小区
					if (CollectionUtils.isEmpty(cellInfos)){
					 	result.setMsg("您没有任何小区的管理权限，请联系管理员");
					 	result.setSuccess(false);
					 	return result;
					}
					user.setCellInfos(cellInfos);
					
					//所有对应的小区里没有任何权限
					if(!menuService.initUserFirstMenuBycell(user , Constants.SYSTEM_OPERATION_WEB)){
						result.setMsg("您没有任何小区的管理权限，请联系管理员");
					 	result.setSuccess(false);
					 	return result;
					}
				}else{
					//平台运营获取所有小区
					cellInfos = cellInfoService.getAllCellInfo();
					user.setCellInfos(cellInfos);
					user.setRoleCellList(roleList);//平台运营在所有小区权限一样
					
					//所有角色里没有任何权限
					if(!menuService.initAdminUserFirstMenu(user , Constants.SYSTEM_OPERATION_WEB)){
						result.setMsg("您没有任何管理权限，请联系管理员");
					 	result.setSuccess(false);
					 	return result;
					}
				}
				
				//修改用户登录次数和登录时间
				userService.updateLoginTimeAndTimes(user);
				
				result.setSuccess(true);
				result.setObj(user);
				result.setMsg("校验通过");
				session.setMaxInactiveInterval(RequestConstants.SessionActionTime);		//设置session超时时间
				session.setAttribute(RequestConstants.USER_SESSION_ID, user);
				session.setAttribute(RequestConstants.MENUS, user.getCellMenus());
				session.setAttribute(RequestConstants.MENUS_ARRAY, menuService.getMenusArrayByCache(user,Constants.SYSTEM_OPERATION_WEB));
				session.setAttribute(RequestConstants.IMAGE_LOGO, Globals.getImageUrl());
				LogUtils.insertLog("用户登录",user.getId(),request);
				
			}else{
				result.setMsg("密码错误");
				result.setSuccess(false);
			}
			
		} catch (Exception e) {
		    e.printStackTrace();
			result.setMsg(RequestConstants.NET_ERROR);
			result.setSuccess(false);
		}
		return result;
	}
	
	/**
	 * @Description 获取角色在当前小区的权限<br>
	 * 
	 * @param cellId 小区id
	 * @param request 用户请求
	 * @param response 服务器响应
	 * @return 
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年5月16日
	 * @see 
	 */
	@RequestMapping(value="getMenuByRoleId" , method = RequestMethod.GET)
	@ResponseBody
	public RequestJson getMenuByRoleId(String cellId,HttpServletRequest request,HttpServletResponse response) {
		RequestJson result = new RequestJson();
		final HttpSession session = request.getSession();
		User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
		
		//取出当前用户在当前小区的角色集合
		List<String> roleCellList = roleService.getRoleListBycellId(cellId,user.getId());
		if(user != null){
			user.setRoleCellList(roleCellList);
			
			List<Menu> menus = null;
			if (user.getRoleList() != null) {
				menus = menuService.getMenusByCache(user , Constants.SYSTEM_OPERATION_WEB);
                
				//取出第一个有效的一级菜单
				Menu first = menus.get(0);
				
				//取出第一个有效可点击的菜单
                //Menu first = menuService.getFirstAvailableMenus(menus);
                user.setMenu(first);
            }
			
			if(user.getMenu() == null){
				result.setMsg("该用户权限不足，无法登陆");
				result.setSuccess(false);
				return result;
			}
			
			result.setSuccess(true);
			result.setObj(user);
			result.setMsg("校验通过");
			session.setMaxInactiveInterval(RequestConstants.SessionActionTime);		//设置session超时时间
			session.setAttribute(RequestConstants.USER_SESSION_ID, user);
			session.setAttribute(RequestConstants.MENUS, menus);
			session.setAttribute(RequestConstants.MENUS_ARRAY, menuService.getMenusArrayByCache(user,Constants.OPERATION_TYPE));
			session.setAttribute(RequestConstants.IMAGE_LOGO, Globals.getImageUrl());
			LogUtils.insertLog("用户登录",user.getId(),request);
		}
		
		
		
		return result;
	}
	
	
	@RequestMapping(value="exist" , method = RequestMethod.GET)
    @ResponseBody
	public RequestJson logout(HttpServletRequest request,HttpServletResponse response) {
	    RequestJson result = new RequestJson();
	    
		final HttpSession session = request.getSession();
		User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
		LogUtils.insertLog("用户退出",user.getId(),request);
		session.setAttribute(RequestConstants.USER_SESSION_ID, null);
		//退出之前清除与当前用户关联的小区seesion
		if(session.getAttribute("roleCells") != null && session.getAttribute("roleCells") != ""){
			session.removeAttribute("roleCells");
		}
		session.invalidate();
		return result;
	}
	
	/**
	 * @Description 返回登录后选择小区页面<br>
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return 
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年5月16日
	 * @see 
	 */
	@RequestMapping(value="selectCell" , method = RequestMethod.GET)
	public String selectCell(Model model,HttpServletRequest request,HttpServletResponse response) {
		
		final HttpSession session = request.getSession();
		User user = (User)session.getAttribute(RequestConstants.USER_SESSION_ID);
		
		List<CellInfo> cellInfos = new ArrayList<CellInfo>();
		
		//根据当前用户的角色list取出每个roleId对应的cellList取并集存入roleCells
		List<String> roleCells = new ArrayList<String>();
		if(CollectionUtils.isNotEmpty(user.getRoleList())){
			for (String roleId : user.getRoleList()) {
				roleCells.addAll(roleService.getCellIdListByRoleId(roleId));
			}
		}
		
		//对roleCells中小区id去重，即取到当前用户绑定的所有小区
		HashSet<String> h = new HashSet<String>(roleCells);
		roleCells.clear();
		roleCells.addAll(h);
		
		
		
		if(CollectionUtils.isNotEmpty(roleCells)){
			//将与当前用户关联的所有小区id存入session
			session.setAttribute("roleCells", roleCells);
			
			//获取根据provinceId后的小区list
			 cellInfos = cellInfoDao.getCellListByCellIds(roleCells);
			 if(CollectionUtils.isNotEmpty(cellInfos)){
				 List<CellInfo> list = new ArrayList<CellInfo>();
				 for(CellInfo item : cellInfos){
					 list = cellInfoService.getCityListByProvinceId(item.getProvinceId(),roleCells);
					 item.setCitys(list);
				 }
				 model.addAttribute("firstProvince",cellInfos.get(0).getCitys());
				 model.addAttribute("firstCity",cellInfoService.getCellListByCityId(cellInfos.get(0).getCitys().get(0).getCityId(), roleCells));
				 model.addAttribute("cellInfos", cellInfos);
			 }
		}else{
			model.addAttribute("errorCell", user.getLoginname()+"没有绑定小区,无法获取权限，请联系管理员!");
		}
		
		return "selectCell";
	}
	
	/**
	 * @Description 通过省id获取与用户绑定的小区所在市市集合<br>
	 * 
	 * @param provinceId 省id
	 * @param request 用户请求
	 * @param response 服务器响应
	 * @return 返回与用户绑定的小区所在市市集合
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年5月16日
	 * @see 
	 */
	@RequestMapping(value="getCityListByProvinceId" , method = RequestMethod.GET)
    @ResponseBody
	public RequestJson getCityListByProvinceId(Integer provinceId,HttpServletRequest request,HttpServletResponse response) {
	    RequestJson result = new RequestJson();
	    final HttpSession session = request.getSession();
	    @SuppressWarnings("unchecked")
		List<String> roleCells =  (List<String>) session.getAttribute("roleCells");
	    try {
			List<CellInfo> infos = cellInfoService.getCityListByProvinceId(provinceId, roleCells);
			infos.get(0).setCells(cellInfoService.getCellListByCityId(infos.get(0).getCityId(), roleCells));
			result.setObj(JSONArray.fromObject(infos).toString());
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * @Description 通过市id获取与用户绑定的小区所在小区集合<br>
	 * 
	 * @param cityId 城市id
	 * @param request用户请求
	 * @param response服务器响应
	 * @return 返回与用户绑定的小区集合
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年5月16日
	 * @see 
	 */
	@RequestMapping(value="getCellListByCityId" , method = RequestMethod.GET)
	@ResponseBody
	public RequestJson getCellListByCityId(Integer cityId,HttpServletRequest request,HttpServletResponse response) {
		RequestJson result = new RequestJson();
	    final HttpSession session = request.getSession();
	    @SuppressWarnings("unchecked")
		List<String> roleCells =  (List<String>) session.getAttribute("roleCells");
	    try {
			List<CellInfo> infos = cellInfoService.getCellListByCityId(cityId, roleCells);
			
			result.setObj(JSONArray.fromObject(infos).toString());
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	 /**
     * 
     * @Description 返回商户身份验证页面
     * 
     * @param model
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月13日
     * @see
     */
    @RequestMapping(value = "userCheck", method = RequestMethod.GET)
    public String userCheck(Model model, HttpServletRequest req) {
        try {
            User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            	model.addAttribute("user", user);
            	String phone = user.getPhone();
            	if(StringUtils.isNotEmpty(phone)){
            	model.addAttribute("type", USER_CHECK);
            	} else {
            		model.addAttribute("type", PHONE_BIND);	
            	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
        
        return "store/bindphone/bindPhone";
        
    }
    
    /**
     * 
     * @Description 返回绑定手机页面
     * 
     * @param model
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月13日
     * @see
     */
    @RequestMapping(value = "bindPhone", method = RequestMethod.GET)
    public String bindPhone(Model model, HttpServletRequest req) {
    	model.addAttribute("type", PHONE_BIND);
    	model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
    	
    	return "store/bindphone/bindPhone";
        
    }
    
    /**
     * 
     * @Description 返回手机绑定完成页面
     * 
     * @param model
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月13日
     * @see
     */
    @RequestMapping(value = "bindComplete", method = RequestMethod.GET)
    public String bindComplete(Model model, HttpServletRequest req) {
    	model.addAttribute("type", PHONE_BIND);
    	
    	return "store/bindphone/bindComplete";
    }
    
    /**
     * 
     * @Description 绑定手机发送验证码信息
     * 
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月12日
     * @see
     */
    @RequestMapping(value = "sendOldPhone", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sendMSG(HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try{
    		 User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    		 String phone = user.getPhone();
    		 //随机生成六位数验证码
    		 String phoneCode = SixCodeUtil.sixCode();
    		 
    		 verifyCodeService.sendCodeMessage(user, phone, phoneCode, result);
    		 
    	}  catch (Exception e) {
             result.setSuccess(false);
             result.setMsg("操作失败");
             e.printStackTrace();
        }

    	return result;
    	
    }
    
    /**
     * 
     * @Description 绑定新手机号发送验证码
     * 
     * @param phone 新手机号
     * @param id 主键id
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月14日
     * @see
     */
    @RequestMapping(value = "sendNewPhone", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson savaPhone(String phone, String id, HttpServletRequest req) {
    	RequestJson result = new RequestJson();
    	try{
    		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
    		user.setPhone(phone);
    		user.setId(id);
    		userService.updateByPrimaryKeySelective(user);
    		//随机生成六位数验证码
    		String phoneCode = SixCodeUtil.sixCode();
    		
    		verifyCodeService.sendCodeMessage(user, phone, phoneCode, result);
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    		result.setSuccess(false);
    		result.setMsg("操作失败");
    	}
    	
    	return result;
    }
    
    /**
     * 
     * @Description 判断输入的登录名是否存在<br>
     * 
     * @param loginName 登录名
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月21日
     * @see
     */
    @RequestMapping(value="isUser" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson isUser(String loginName,HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
        	User user = userService.selectByPhone(loginName);
        	if (user != null ){
        		result.setObj(user.getPhone());

        	} else {
        		result.setObj(loginName);
        		
        	}
        	result.setSuccess(true);
        	result.setMsg("操作成功");
        	
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        
        return result;
     
}
    
    /**
     * 
     * @Description 返回找回密码页面<br>
     * 
     * @param model
     * @param loginName 用户登录名
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月21日
     * @see
     */
    @RequestMapping(value = "findPassword", method = RequestMethod.GET)
    public String findPassword( Model model,String loginName, HttpServletRequest req) {
    	try{
    		if(StringUtils.isNotEmpty(loginName)){
    			User user = userService.selectByPhone(loginName);
    			model.addAttribute("user", user);
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
    	
    	return "common/findPassword";
        
    }
    
    /**
     * 
     * @Description 忘记密码发送验证码修改密码<br>
     * 
     * @param name 登录名
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月16日
     * @see
     */
    @RequestMapping(value = "sendCode", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sendCode(String lname, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try{
    		 User user = userService.selectByPhone(lname);
    		 if (user != null){
    			 String phone = user.getPhone();
    			 //随机生成六位数验证码
    			 String phoneCode = SixCodeUtil.sixCode();
    			 
    			 verifyCodeService.sendCodeMessage(user, phone, phoneCode, result);
    			 
    		 }
    	}  catch (Exception e) {
             result.setSuccess(false);
             result.setMsg("操作失败");
             e.printStackTrace();
        }
    	
		return result;
    }
    
    /**
     * 
     * @Description 保存新密码<br>
     * 
     * @param loginName 用户登录名
     * @param newPwd 新密码
     * @param req 用户请求
     * @return 
     * @author lilan 1063972142@qq.com
     * @date 2016年6月21日
     * @see
     */
    @RequestMapping(value="completePassword" , method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateAdInfo(String loginName,String newPwd,HttpServletRequest req){
        RequestJson result = new RequestJson();
        User user = userService.selectByPhone(loginName);
        user.setPwd(newPwd);
        try {
            //生成密匙
//            final String newUserKey = MD5Util.generalPassword(loginName,newPwd);
            user.setPwd(newPwd);
            userService.updateByPrimaryKeySelective(user);
            
            result.setSuccess(true);
            result.setMsg("操作成功");
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        
        return result;
     
}
	
}
